package com.atguigu.gmall.product.util;

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;

/***
 * 文件上传、下载、删除工具类
 */
public class FileUtils {

    /**
     * 初始化fastDFS
     */
    static {
        ClassPathResource classPathResource = new ClassPathResource("tracker.conf");
        try {
            ClientGlobal.init(classPathResource.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     *
     * @return
     */
    public static String fileUpload(MultipartFile file) throws Exception {

        //初始化tracker
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer storageServer = trackerClient.getConnection();

        //通过tracker获取storage
        StorageClient storageClient = new StorageClient(storageServer, null);

        //上传文件
        String filenameExtension = StringUtils.getFilenameExtension(file.getOriginalFilename());//获取文件的扩展名
        String[] strings = storageClient.upload_file(file.getBytes(), filenameExtension, null);

        return strings[0] + "/" + strings[1];
    }

    public static void fileDownload(String groupName,String fileName) throws Exception {
        //初始化tracker
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer storageServer = trackerClient.getConnection();

        //通过tracker获取storage
        StorageClient storageClient = new StorageClient(storageServer, null);

        //下载图片
        byte[] downloadFile = storageClient.download_file(groupName, fileName);

        //输出到本地
        FileOutputStream fileOutputStream = new FileOutputStream("D:/1.jpg");
        fileOutputStream.write(downloadFile);
    }

    public static void main(String[] args) throws Exception {
        fileDownload("group1","M00/00/03/wKjIgGP3aWuAE0IbAAcqIYxFN7I049.jpg");
    }

}
